/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.javlov.vf;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import net.javlov.State;

public class ValueMap<T> implements ValueTable<T> {

	private static final long serialVersionUID = -8072878479803970864L;

	protected Map<State<? extends T>, Value> table;
	
	protected ValueFunction<T> initializer;
	
	public ValueMap() {
		this(1000);
	}
	
	public ValueMap(int size) {
		table = new HashMap<State<? extends T>, Value>(size);
	}
	
	public double getInitialValue(State<? extends T> s) {
		if ( initializer == null )
			return 0;
		return initializer.getValue(s);
	}
	
	public void setInitializer(ValueFunction<T> vf) {
		initializer = vf;
	}
	
	public double getValue(State<? extends T> s) {
		return get(s).get();
	}
	
	public void setValue(State<? extends T> s, double val) {
		Value v = get(s);
		v.set(val);
	}

	@Override
	public void init() {
		table.clear();		
	}

	public void reset() {}
	
	@Override
	public Double queryValue(State<? extends T> s) {
		Value val = table.get(s);
		if ( val == null )
			return null;
		return val.get();
	}

	@Override
	public void update(State<? extends T> s, double delta) {
		Value val = table.get(s);
		if ( val == null )
			throw new UnknownStateException(s.toString());
		val.add(delta);
	}
	
	@Override
	public Value get(State<? extends T> s) {
		Value val = table.get(s);
		if ( val == null ) {
			val = new Value( getInitialValue(s) );
			table.put(s, val);
		}
		return val;
	}

	@Override
	public void set(State<? extends T> s, Value val) {
		table.put(s, val);		
	}

	@Override
	public int size() {
		return table.size();
	}
	
	@Override
	public String toString() {
		String s = "";
		for ( Map.Entry<State<? extends T>, Value> e : table.entrySet() )
			s += e.toString() + "\n";
		return s;
	}
	
	public Set<State<? extends T>> states() {
		return table.keySet();
	}
	
	public Collection<Value> values() {
		return table.values();
	}
	
	public Set<Map.Entry<State<? extends T>, Value>> stateValueSet() {
		return table.entrySet();
	}
	
}
